<?php
/* class represents the facebook api and 
 * follows the documentation under:
 * 
 * http://developers.facebook.com/docs/authentication/
 * 
 * */
class facebook{
	const LOCAL_COOKIE_NAME = "facebook_token";
	
	// the cache for storing api results
	public $cache;
	
	// Important: Read the information below in the 
	//				constructor where the value is set
	public $REDIRECT_URI = "";
	
	// indicates whether the user just logged in or 
	// was logged in already before. This is mostly
	// just for the import of users into the database
	public $isNewUser = false;
	
	// defines whether user is logged in or not
	private $isLoggedIn = false;
	
	// holds the access token for the api
	private $accessToken = "";
	private $tokenExpiry = 0;
	
	// facebook application credentials
	private $appId = CONFIG_FACEBOOK_APPID;
	private $appSecret = CONFIG_FACEBOOK_APPSECRET;
	
	/* constructor checks for authentication */
	public function __construct(){
		/* create an instance of the cache */
		$this->cache = new cache();
		
		/* Important: In order to get the oauth token when need to supply a proper
		 * 				redirect url both when the client redirects as well as when
		 * 				we call the token in the end. This URL needs to have the 
		 * 				protocol, the server name and the name of the redirect file. */
		$this->REDIRECT_URI = urlencode("http://".$_SERVER["SERVER_NAME"]."/index.php");
		
		/* when the logout GET param exists, we drop the cookie */
		if(array_key_exists("logout", $_GET)){
			// disable the cookie
			setcookie(facebook::LOCAL_COOKIE_NAME,"",(time()-1000));
		}else{
			/* check for the token cookie we created */
			if(array_key_exists(facebook::LOCAL_COOKIE_NAME, $_COOKIE)){
				// set it locally when it exists
				$this->accessToken = $_COOKIE[facebook::LOCAL_COOKIE_NAME];
				// set local login indicator to true
				$this->isLoggedIn = true;
			}else{
				/* check whether the code exists or not */
				if(array_key_exists("code", $_GET)){
					// get the token, the expiry and set a cookie
					$token_url = "https://graph.facebook.com/oauth/access_token?client_id="
		        			.$this->appId."&redirect_uri=".$this->REDIRECT_URI
		        			."&client_secret=".$this->appSecret
		        			."&code=".$_GET["code"];
		
		        	// call the token url and get the values
					$token_result = explode("&",file_get_contents($token_url));
					$token_value = explode("=",$token_result[0]);
					$token_expiry = explode("=",$token_result[1]);
					$token = $token_value[1];
					$expiry = $token_expiry[1];
					
					// store the token locally
					$this->accessToken = $token;
					$this->tokenExpiry = (time()+$expiry);
					
					// finally set the token cookie
					setcookie(facebook::LOCAL_COOKIE_NAME,$token,$this->tokenExpiry);
					
					// set logged in to true
					$this->isLoggedIn = true;
					
					// also indicate that this is a new user
					$this->isNewUser = true;
				}
			}
		}
	}
	
	// checks whether the user is logged in or not
	// by checking whether the cookies exists or not
	public function isLoggedIn(){
		return $this->isLoggedIn;
	}

	
	// returns the user details or null, when not logged in
	public function getUser(){
		$user = null;
		
		// once user is logged in, fetch the details
		// from facebook
		if($this->isLoggedIn()){
			/* build the url for the call */
			$api_url = "https://graph.facebook.com/me"
						."?access_token=".$this->accessToken;
			
			/* build the cache key for this call */
			$cache_key = $this->cache->hash("facebook".$api_url);
						
			/* check whether the cache has results or not */
			if($this->cache->has($cache_key)){
				// the data is present
				$user = $this->cache->get($cache_key);
			}else{
				// data is not present, call it and cache it
				$user = json_decode(file_get_contents($api_url));
				
				// keep cached for an hour
				$this->cache->put($cache_key, $user, time()+3600);
			}
		}
		
    	return $user;
	}
}
?>